import request from "../../utils/http";
import { promisify, wxBack } from "../../utils/util";

// pages/login/login.ts
Page({

	/**
	 * 页面的初始数据
	 */
	data: {

	},

	async getPhoneNumber(e: any) {
		console.log(e)
		if (!e.detail.code) return;
		wx.showLoading({title: '正在登录...'});
		const { code } = await promisify(wx.login);
		console.log({
			...e.detail,
			phoneCode: e.detail.code,
			code,
		});
		try {
			const data = await request({
				url: '/api/customers/wechat/phoneLogin',
				method: 'POST',
				data: {
					// ...e.detail,
					phoneCode: e.detail.code,
					code,
				},
				errToast: true,
				contentTypeForm: true
			});
			const app = getApp();

			app.globalData.token = data.token;
			app.globalData.openid = data.openid;
			wx.setStorageSync("token", data.token);
			wx.setStorageSync("openid", data.openid);
			wx.setStorageSync("phone", data.phone);
			if (data.userInfo) {
				wx.setStorageSync("userInfo", JSON.stringify(data.userInfo));
				app.globalData.userInfo = data.userInfo;
			}
			wxBack({});
		} catch (error) {
			console.warn("error: ", error);
		} finally {
			wx.hideLoading();
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad() {

	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})